package com.nirvana.utils.json;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

/**
 * Date类型的值处理器
 * @author Sue
 *
 */
public class DateValueProcessor implements JsonValueProcessor {
	
	private static Log log = LogFactory.getLog(DateValueProcessor.class);
	
	//默认的输出格式为yyyy-MM-dd
	private String format = "yyyy-MM-dd";

	
	public DateValueProcessor(String format) {
		super();
		this.format = format;
	}

	public DateValueProcessor() {
	}

	@Override
	public Object processArrayValue(Object obj, JsonConfig jsonConfig) {
		log.info("dateFormat:" + format);
		String[] returnObj = {};
		if(obj == null)
			return null;
		if(obj instanceof Date[]){
			SimpleDateFormat dFormat = new SimpleDateFormat(format);
			Date[] dateArray = (Date[]) obj;
			returnObj = new String[dateArray.length];
			for( int i = 0;i < dateArray.length;i++){
				returnObj[i] = dFormat.format(dateArray[i]);
			}
		}
		return returnObj;
	}

	@Override
	public Object processObjectValue(String key, Object obj, JsonConfig jsonConfig) {
		log.info("dateFormat:" + format);
		if(obj == null)
			return null;
		if(obj instanceof Date){
			String dateStr = new SimpleDateFormat(format).format((Date)obj);
			return dateStr;
		}
		return obj;	 
	}
	
}
